package com.yonyou.pmclouds.billview.plugin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import com.yonyou.pmclouds.basecom.util.StorageFactory;
import com.yonyou.pmclouds.businessobject.util.BusinessObjectConsts;
import com.yonyou.pmclouds.businessobject.util.PrintPreviewObj2Html;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseVO;
import com.yonyou.pmclouds.enterprise.rmiitf.EnterpriseQuery;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.workflow.service.rmiitf.IWorkFlowService;
import com.yonyou.pmclouds.workquality.entity.WorkqualityVO;
import com.yonyou.pmclouds.workquality.service.rmiitf.WorkqualityQueryService;
import com.yonyou.pmclouds.workstartreport.entity.WorkStartCheckVO;
import com.yonyou.pmclouds.workstartreport.entity.WorkStartVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class WorkStartPlugin implements IBillViewCustomPlugin {

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private EnterpriseQuery enterpriseQuery;
    @Autowired
    private UserInfoQuery userInfoQuery;
    @Autowired
    private StorageFactory storageFactory;

    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private ProjectSimpleQuery projectSimpleQuery;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private IWorkFlowService iworkFlowService;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private WorkqualityQueryService workqualityQueryService;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private OrganizationQuery organizationQuery;
    @Value("${print.perLineNum}")
    private int perLineNum;
    @Override
    public Object[] fillListBuziField(Object[] objects) throws BusinessException {
        //施工单位
        Set<String> constructionUnitPks = new HashSet<>();
        WorkStartVO[] workStartVOSS=new WorkStartVO[objects.length];
        for (int i = 0; i < objects.length ; i++){
            workStartVOSS[i]=(WorkStartVO)objects[i];
        }

        // 取到所有施工单位的pk,获取施工单位信息
        for (WorkStartVO workStartVO : workStartVOSS) {
            constructionUnitPks.add(workStartVO.getPkEnterprise());
            if(StringUtils.isNotBlank(workStartVO.getPkSupervision()) && !constructionUnitPks.contains(workStartVO.getPkSupervision())){
                constructionUnitPks.add(workStartVO.getPkSupervision());
            }
        }
        EnterpriseVO[] enterpriseVOS = enterpriseQuery.queryByIds(constructionUnitPks.toArray(new String[0]));
        if(enterpriseVOS != null && enterpriseVOS.length > 0){
            Map<String, String> enterpriseInfoMap = Arrays.stream(enterpriseVOS).filter(vo -> StringUtils.isNotEmpty(vo.getName())).collect(Collectors.toMap(EnterpriseVO::getPkEnterprise, EnterpriseVO::getName, (v1,v2)-> v1));
            for (WorkStartVO workStartVO : workStartVOSS) {
                //设置施工单位名称
                workStartVO.setEnterpriseName(enterpriseInfoMap.get(workStartVO.getPkEnterprise())==null?"":enterpriseInfoMap.get(workStartVO.getPkEnterprise()));
                //设置监理单位名称
                workStartVO.setSupervisionName(enterpriseInfoMap.get(workStartVO.getPkSupervision())==null?"":enterpriseInfoMap.get(workStartVO.getPkSupervision()));
            }
        }
//        //监理单位
//        enterpriseQuery.tranEntInfoField(workStartVOSS, new String[]{WorkStartVO.PK_SUPERVISION}, new String[]{WorkStartVO.SUPERVISION_NAME});
        List<String> pkPorjects = Arrays.stream(workStartVOSS).map(WorkStartVO::getPkProject).collect(Collectors.toList());
        List<String> pkWorkqualitys = Arrays.stream(workStartVOSS).map(WorkStartVO::getPkWorkquality).collect(Collectors.toList());
        //获取所有项目以及项目对应的组织名称
        Map<String, ProjectVO> projectMap = projectSimpleQuery.queryProjects(pkPorjects.toArray(new String[0]));
        //获取组织信息
        Map<String, OrganizationVO> proToOrgMap = obtailPkorgByProject(projectMap);
        //获取条件信息
        Map<String, WorkqualityVO> stringWorkqualityVOMap = workqualityQueryService.queryByIDs(pkWorkqualitys.toArray(new String[0]));
        //补充项目、组织、条件信息
        wrapstartVo(workStartVOSS, projectMap, proToOrgMap, stringWorkqualityVOMap);

        return workStartVOSS;
    }

    @Override
    public Map<String,Object[]> fillDetailBuziField(SuperVO superVO, HttpServletRequest request) throws BusinessException {

        //获取返回的单据检查项
        WorkStartCheckVO[] workStartCheckVOS=(WorkStartCheckVO[]) BeanHelper.getProperty(superVO, "workStartCheckVOS");

        //补充创建者姓名
        userInfoQuery.tranUserInfoField(new Object[]{superVO},new String[]{CommonFieldConst.CREATOR},new String[]{CommonFieldConst.CREATOR_NAME});
        //获取施工方ID
        String pkEnterprise = BeanHelper.getProperty(superVO,"pkEnterprise")==null?"":(String)BeanHelper.getProperty(superVO,"pkEnterprise");
        String pkSupervision = ((WorkStartVO)superVO).getPkSupervision();


        EnterpriseVO[] enterpriseVOS = enterpriseQuery.queryByIds(new String[]{pkEnterprise, pkSupervision});

        if(enterpriseVOS != null && enterpriseVOS.length > 0){
            Map<String, String> enterpriseMap = Arrays.stream(enterpriseVOS).collect(Collectors.toMap(EnterpriseVO::getPkEnterprise, EnterpriseVO::getName));
            //补充施工方名称
            BeanHelper.setProperty(superVO,"enterpriseName",enterpriseMap.get(pkEnterprise) ==null ?"" :enterpriseMap.get(pkEnterprise));
            ((WorkStartVO)superVO).setSupervisionName(enterpriseMap.get(pkSupervision) ==null ?"" :enterpriseMap.get(pkSupervision));
        }

        PrintPreviewObj2Html obj2Html = new PrintPreviewObj2Html(PrintPreviewObj2Html.BASE_PREFIX, PrintPreviewObj2Html.IMG, perLineNum);

        if (workStartCheckVOS != null) {
            for (WorkStartCheckVO workStartCheckVO : workStartCheckVOS) {
                if (workStartCheckVO.getPictures() != null) {
                    //转换图片解析为HTML
                    String picHtml = obj2Html.urls2Html(storageFactory.getStorageUtil().signUrlForMultiPictures(workStartCheckVO.getPictures(), null, request));
                    workStartCheckVO.setPicture_address(picHtml);
                }
            }
            BeanHelper.setProperty(superVO,"workStartCheckVOS",workStartCheckVOS);
        }

        Map<String,Object[]> resultMap = new HashMap<String,Object[]>();

        resultMap.put(BusinessObjectConsts.PM_WORKSTART, new Object[]{superVO});
        resultMap.put(BusinessObjectConsts.PM_WORKSTARTCHECK, workStartCheckVOS);

        return resultMap;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.WORKSTART_BILLTYPE;
    }

    private Map<String, OrganizationVO> obtailPkorgByProject(Map<String, ProjectVO> projectMap) throws BusinessException {
        Map<String, OrganizationVO> proToOrgMap = new HashMap<String, OrganizationVO>();
        if(projectMap != null && projectMap.size()> 0){
            List<String> pkOrgs = projectMap.values().stream().map(ProjectVO::getPkOrg).filter(vo -> StringUtils.isNotEmpty(vo)).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(pkOrgs)) {
                OrganizationVO[] organizationVOs = organizationQuery.queryByPkSrcs(RuntimeEnvironment.getTenantId(), pkOrgs.toArray(new String[0]));
                proToOrgMap = Arrays.stream(organizationVOs).filter(organizationVO -> StringUtils.isNotEmpty(organizationVO.getPkSrc()))
                        .collect(Collectors.toMap(OrganizationVO::getPkSrc, organizationVO -> organizationVO));
            }
        }
        return proToOrgMap;
    }

    /**
     * 封装项目 组织 条件信息
     * @param workStartVOS
     * @param projectMap
     * @param proToOrgMap
     * @param stringWorkqualityVOMap
     * @throws BusinessException
     */
    private void wrapstartVo(WorkStartVO[] workStartVOS, Map<String, ProjectVO> projectMap, Map<String, OrganizationVO> proToOrgMap, Map<String, WorkqualityVO> stringWorkqualityVOMap) throws BusinessException {
        String loginUserId = RuntimeEnvironment.getLoginUserId();
        for (WorkStartVO workStartVO : workStartVOS) {
            String pkTenant = workStartVO.getPkTenant();
            //获取条件信息
            WorkqualityVO workqualityVO = stringWorkqualityVOMap.get(workStartVO.getPkWorkquality());
            if(workqualityVO != null && StringUtils.isNotBlank(workqualityVO.getCheckname())){
                //赋值条件名
                workStartVO.setConditionName(workqualityVO.getCheckname());
            }
            //获取项目信息
            ProjectVO projectVO = projectMap.get(workStartVO.getPkProject());
            if(projectVO != null){
                //赋值项目名以及项目编号
                workStartVO.setProjectName(projectVO.getSname());
                workStartVO.setProjectCode(projectVO.getScode());
            }
            workStartVO.setCanApprove(false);
            boolean b = iworkFlowService.checkApprovePerm(workStartVO.getPkWorkstartreport(), loginUserId);
            if(b){
                workStartVO.setCanApprove(true);
            }
            if(proToOrgMap.get(projectVO.getPkOrg()) != null){
                OrganizationVO organizationVO = proToOrgMap.get(projectVO.getPkOrg());
                workStartVO.setPkOrganization(organizationVO.getPkOrganization());
                workStartVO.setOrgName(organizationVO.getSname());
                workStartVO.setPkOrgSrc(organizationVO.getPkSrc());
            }

//            if (pkTenant != null) {
//                List<WorkqualityVO> workqualityVOS = workqualityQueryService.queryByChecktypes(pkTenant, WorkqualityCheckTypeEnum.CONDITION.getValue());
//                workStartVO.setWorkqualityCount(workqualityVOS.size());
//            }
//            WorkStartCheckVO[] workStartCheckVOS = checkMapper.selectAllCheck(workStartVO.getPkWorkquality(), workStartVO.getPkWorkstartreport());
//            workStartVO.setWorkStartCheckVOS(workStartCheckVOS);
//            //获取不具备检查项数量
//            Integer checkCount = checkMapper.selectCount(workStartVO.getPkWorkstartreport(), pkTenant);
//            workStartVO.setCheckCount(checkCount);
        }
    }
}
